package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.his.po.Register;
import com.neuedu.his.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 挂号管理控制器
 * 处理挂号登记、查询、更新等业务逻辑
 */
@RestController
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    /**
     * 新增挂号记录
     * @param register 挂号信息
     * @return 操作结果
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> add(@RequestBody Register register) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 手动校验必要参数
            if (register.getRealname() == null || register.getDeptid() == null ||
                    register.getVisitdate() == null || register.getRegistleid() == null) {
                result.put("success", false);
                result.put("message", "姓名、科室、看诊日期和挂号级别为必填项");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 设置默认值
            register.setRegisttime(new Date());       // 挂号时间
            register.setVisitstate(1);                // 默认看诊状态为"待就诊"
            register.setIsbook("否");                 // 默认不需要病历本

            boolean saveResult = registerService.save(register);
            result.put("success", saveResult);
            result.put("message", saveResult ? "挂号登记成功" : "挂号登记失败");
            result.put("data", register);

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "挂号登记失败：" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 根据ID查询挂号详情
     * @param id 挂号记录ID
     * @return 挂号详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getById(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (id == null || id <= 0) {
                result.put("success", false);
                result.put("message", "ID参数无效");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            Register register = registerService.getById(id);
            if (register == null) {
                result.put("success", false);
                result.put("message", "未找到该挂号记录");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", register);

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 更新挂号记录
     * @param register 挂号信息
     * @return 操作结果
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> update(@RequestBody Register register) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 校验必要参数
            if (register.getId() == null || register.getId() <= 0) {
                result.put("success", false);
                result.put("message", "ID参数无效");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 检查记录是否存在
            Register existRegister = registerService.getById(register.getId());
            if (existRegister == null) {
                result.put("success", false);
                result.put("message", "未找到该挂号记录");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }

            // 只更新允许修改的字段
            Register updateRegister = new Register();
            updateRegister.setId(register.getId());
            updateRegister.setVisitstate(register.getVisitstate());
            updateRegister.setNoon(register.getNoon());
            updateRegister.setUserid(register.getUserid());

            boolean updateResult = registerService.updateById(updateRegister);
            result.put("success", updateResult);
            result.put("message", updateResult ? "更新成功" : "更新失败");

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 删除挂号记录（逻辑删除）
     * @param id 挂号记录ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> delete(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (id == null || id <= 0) {
                result.put("success", false);
                result.put("message", "ID参数无效");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 检查记录是否存在
            Register register = registerService.getById(id);
            if (register == null) {
                result.put("success", false);
                result.put("message", "未找到该挂号记录");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }

            // 逻辑删除
            register.setVisitstate(9); // 设为已删除状态
            boolean deleteResult = registerService.updateById(register);
            result.put("success", deleteResult);
            result.put("message", deleteResult ? "删除成功" : "删除失败");

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 分页查询挂号记录
     * @param page 当前页码
     * @param pageSize 每页记录数
     * @param realname 患者姓名（可选）
     * @param deptid 科室ID（可选）
     * @param visitstate 看诊状态（可选）
     * @return 分页结果
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String realname,
            @RequestParam(required = false) Integer deptid,
            @RequestParam(required = false) Integer visitstate) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 构建分页对象
            Page<Register> pageParam = new Page<>(page, pageSize);

            // 构建查询条件
            LambdaQueryWrapper<Register> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(realname != null, Register::getRealname, realname);
            wrapper.eq(deptid != null, Register::getDeptid, deptid);
            wrapper.eq(visitstate != null, Register::getVisitstate, visitstate);
            wrapper.orderByDesc(Register::getRegisttime); // 按挂号时间降序排列

            // 执行查询
            IPage<Register> registerPage = registerService.page(pageParam, wrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", registerPage);

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 根据科室ID统计当天挂号人数
     * @param deptid 科室ID
     * @return 挂号人数
     */
    @GetMapping("/count/today/{deptid}")
    public ResponseEntity<Map<String, Object>> countTodayRegistrations(@PathVariable Integer deptid) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (deptid == null || deptid <= 0) {
                result.put("success", false);
                result.put("message", "科室ID无效");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 构建查询条件（当天挂号且科室匹配）
            LambdaQueryWrapper<Register> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Register::getDeptid, deptid);
            wrapper.ge(Register::getRegisttime, new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000));
            wrapper.le(Register::getRegisttime, new Date());

            long count = registerService.count(wrapper);

            result.put("success", true);
            result.put("message", "统计成功");
            result.put("data", count);

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "统计失败：" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 更新挂号状态（如：就诊中、已完成）
     * @param id 挂号记录ID
     * @param visitstate 新的看诊状态
     * @return 操作结果
     */
    @PutMapping("/updateState/{id}/{visitstate}")
    public ResponseEntity<Map<String, Object>> updateState(
            @PathVariable Integer id,
            @PathVariable Integer visitstate) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (id == null || id <= 0 || visitstate == null) {
                result.put("success", false);
                result.put("message", "参数无效");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 检查记录是否存在
            Register register = registerService.getById(id);
            if (register == null) {
                result.put("success", false);
                result.put("message", "未找到该挂号记录");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }

            // 更新状态
            register.setVisitstate(visitstate);
            boolean updateResult = registerService.updateById(register);

            result.put("success", updateResult);
            result.put("message", updateResult ? "状态更新成功" : "状态更新失败");

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "状态更新失败：" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 根据医生ID查询当天挂号列表
     * @param userid 医生ID
     * @param date 日期（格式：yyyy-MM-dd）
     * @return 挂号列表
     */
    @GetMapping("/doctor/list/{userid}")
    public ResponseEntity<Map<String, Object>> getDoctorRegistrations(
            @PathVariable Integer userid,
            @RequestParam String date) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (userid == null || userid <= 0 || date == null || date.isEmpty()) {
                result.put("success", false);
                result.put("message", "参数无效");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 解析日期
            Date startDate = new Date(date + " 00:00:00");
            Date endDate = new Date(date + " 23:59:59");

            // 构建查询条件
            LambdaQueryWrapper<Register> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Register::getUserid, userid);
            wrapper.between(Register::getVisitdate, startDate, endDate);
            wrapper.orderByAsc(Register::getNoon); // 按上午/下午排序

            List<Register> registrations = registerService.list(wrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", registrations);

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}